import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:async';
import '../models/chunk_upload.dart';
import '../services/upload/core/upload_manager.dart';
import '../widgets/upload_task_item.dart';
import '../widgets/file_picker_button.dart';
import '../pages/upload_help_page.dart';
import '../services/upload/chunk_upload_service.dart';

class UploadTasksScreen extends StatefulWidget {
  final Function? onUploadComplete;

  const UploadTasksScreen({super.key, this.onUploadComplete});

  @override
  State<UploadTasksScreen> createState() => _UploadTasksScreenState();
}

class _UploadTasksScreenState extends State<UploadTasksScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final UploadManager _uploadManager = UploadManager();
  StreamSubscription? _largeFileSubscription;
  StreamSubscription? _taskUpdateSubscription;

  // 标记是否有完成的任务
  bool _hasCompletedTasks = false;

  // 为每个标签页添加一个键，用于强制刷新
  final _activeTabKey = GlobalKey();
  final _completedTabKey = GlobalKey();

  // 添加一个状态变量跟踪上次刷新时间
  DateTime _lastActiveRefresh = DateTime.now();
  DateTime _lastCompletedRefresh = DateTime.now();

  // 用于强制刷新StreamBuilder的键
  Key _activeStreamKey = UniqueKey();
  Key _completedStreamKey = UniqueKey();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);

    // 监听标签切换事件
    _tabController.addListener(_handleTabChange);

    // 监听任务状态更新
    _taskUpdateSubscription = ChunkUploadService.uploadTasksStream.listen((
      tasks,
    ) {
      // 任务数据更新时，强制刷新当前标签页
      if (mounted) {
        // 检查是否有任务刚刚完成，如果有且当前不在已完成标签，也需要刷新已完成标签
        bool hasNewlyCompletedTask = false;

        for (final task in tasks) {
          if (task.status == UploadTaskStatus.completed &&
              task.completedAt != null &&
              DateTime.now().difference(task.completedAt!).inSeconds < 3) {
            // 发现刚完成的任务（3秒内完成）
            hasNewlyCompletedTask = true;
            _hasCompletedTasks = true; // 设置标记
            print('【检测到新完成任务】${task.fileName} - 完成时间: ${task.completedAt}');
            break;
          }
        }

        setState(() {
          // 更新流构建器的键，强制其重建
          if (_tabController.index == 0) {
            _activeStreamKey = UniqueKey();
            // 日志输出已关闭
            // print('任务状态更新：刷新活动任务列表');

            // 如果检测到新完成的任务，也刷新已完成标签页
            if (hasNewlyCompletedTask) {
              _completedStreamKey = UniqueKey();
              print('检测到新完成任务，同时刷新已完成任务列表');
            }
          } else {
            _completedStreamKey = UniqueKey();
            // 日志输出已关闭
            // print('任务状态更新：刷新已完成任务列表');
          }
        });
      }
    });

    // 监听大文件通知
    _largeFileSubscription = _uploadManager.largeFileNotificationStream.listen((
      fileName,
    ) {
      if (mounted) {
        // 先移除当前所有 SnackBar
        ScaffoldMessenger.of(context).removeCurrentSnackBar();

        // 显示新的通知，设置更长的显示时间
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('文件"$fileName"正在使用断点续传功能，支持暂停和恢复，上传更稳定'),
            duration: const Duration(seconds: 5),
            behavior: SnackBarBehavior.floating,
            action: SnackBarAction(label: '知道了', onPressed: () {}),
          ),
        );
      }
    });
  }

  // 处理标签切换事件
  void _handleTabChange() {
    if (!_tabController.indexIsChanging) {
      // 标签已经完成切换
      // 检查上次刷新是否超过一定时间（例如500毫秒）
      final now = DateTime.now();
      if (_tabController.index == 0) {
        if (now.difference(_lastActiveRefresh).inMilliseconds > 500) {
          _lastActiveRefresh = now;
          print('切换到"上传任务"标签页，触发更新');
          // 获取并打印所有任务的当前状态，帮助调试
          final tasks = ChunkUploadService.uploadTasks;
          for (final task in tasks) {
            print('【切换检查】任务 ${task.fileName} - 当前状态: ${task.status}');
          }
          setState(() {
            // 更新键以强制刷新
            _activeStreamKey = UniqueKey();
          });
        }
      } else {
        if (now.difference(_lastCompletedRefresh).inMilliseconds > 500) {
          _lastCompletedRefresh = now;
          print('切换到"已完成"标签页，触发更新');
          // 获取并打印所有任务的当前状态，帮助调试
          final tasks = ChunkUploadService.uploadTasks;
          for (final task in tasks) {
            print('【切换检查】任务 ${task.fileName} - 当前状态: ${task.status}');
          }
          setState(() {
            // 更新键以强制刷新
            _completedStreamKey = UniqueKey();
          });
        }
      }
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    _largeFileSubscription?.cancel();
    _taskUpdateSubscription?.cancel();
    super.dispose();
  }

  // 重试所有失败或暂停的任务
  void _retryAllFailedTasks() {
    final tasks = ChunkUploadService.uploadTasks;
    int retriedCount = 0;

    for (final task in tasks) {
      if (task.status == UploadTaskStatus.failed ||
          task.status == UploadTaskStatus.paused) {
        ChunkUploadService.resumeUploadTask(task.id);
        retriedCount++;
      }
    }

    // 显示重试任务数量的提示
    if (retriedCount > 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('已重新开始 $retriedCount 个任务'),
          duration: const Duration(seconds: 2),
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('没有需要重试的任务'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return WillPopScope(
      onWillPop: () async {
        // 如果有任务完成，调用回调通知上一页刷新
        if (_hasCompletedTasks && widget.onUploadComplete != null) {
          widget.onUploadComplete!();
        }
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('上传任务'),
          scrolledUnderElevation: 0,
          bottom: TabBar(
            controller: _tabController,
            tabs: const [
              Tab(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.upload_file),
                    SizedBox(width: 8),
                    Text('上传任务'),
                  ],
                ),
              ),
              Tab(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.task_alt),
                    SizedBox(width: 8),
                    Text('已完成'),
                  ],
                ),
              ),
            ],
            indicatorSize: TabBarIndicatorSize.tab,
            dividerColor: Colors.transparent,
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: () {
                _retryAllFailedTasks();
              },
              tooltip: '全部重试',
            ),
            IconButton(
              icon: const Icon(Icons.delete_sweep),
              onPressed: () {
                ChunkUploadService.clearCompletedTasks();
              },
              tooltip: '清除已完成',
            ),
          ],
        ),
        body: TabBarView(
          controller: _tabController,
          children: [
            KeyedSubtree(key: _activeTabKey, child: _buildActiveTasksList()),
            KeyedSubtree(
              key: _completedTabKey,
              child: _buildCompletedTasksList(),
            ),
          ],
        ),
      ),
    );
  }

  // 构建进行中的任务列表
  Widget _buildActiveTasksList() {
    // 日志输出已关闭
    // print('构建活动任务列表组件');
    return StreamBuilder<List<UploadTask>>(
      key: _activeStreamKey,
      stream: ChunkUploadService.uploadTasksStream,
      initialData: ChunkUploadService.uploadTasks,
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text('正在加载...'),
              ],
            ),
          );
        }

        final tasks = List<UploadTask>.from(ChunkUploadService.uploadTasks);
        // 日志输出已关闭
        // print('活动任务列表 - 获取最新数据 - 总任务数: ${tasks.length}');

        final activeTasks =
            tasks.where((task) {
              final isActive =
                  task.status == UploadTaskStatus.pending ||
                  task.status == UploadTaskStatus.uploading ||
                  task.status == UploadTaskStatus.paused ||
                  task.status == UploadTaskStatus.failed;
              // 日志输出已关闭
              // print(
              //   '【活动】检查任务 ${task.fileName} - 状态: ${task.status}, 是否活动: $isActive',
              // );
              return isActive;
            }).toList();

        activeTasks.sort((a, b) {
          if (a.status == UploadTaskStatus.uploading &&
              b.status != UploadTaskStatus.uploading) {
            return -1;
          }
          if (b.status == UploadTaskStatus.uploading &&
              a.status != UploadTaskStatus.uploading) {
            return 1;
          }
          if (a.status == UploadTaskStatus.uploading &&
              b.status == UploadTaskStatus.uploading) {
            return a.createdAt.compareTo(b.createdAt);
          }
          return a.createdAt.compareTo(b.createdAt);
        });

        print('活动任务数: ${activeTasks.length}');

        if (activeTasks.isEmpty) {
          // 日志输出已关闭
          // print('活动任务数: ${activeTasks.length}');
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ShaderMask(
                  shaderCallback: (Rect bounds) {
                    return LinearGradient(
                      colors: [
                        Theme.of(context).colorScheme.primary,
                        Theme.of(context).colorScheme.secondary,
                      ],
                    ).createShader(bounds);
                  },
                  child: const Icon(Icons.cloud_upload_outlined, size: 64),
                ),
                const SizedBox(height: 16),
                Text(
                  '没有进行中的上传任务',
                  style: TextStyle(
                    fontSize: 16,
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          key: ValueKey(
            'active_tasks_${DateTime.now().millisecondsSinceEpoch}',
          ),
          itemCount: activeTasks.length,
          padding: const EdgeInsets.all(16),
          itemBuilder: (context, index) {
            final task = activeTasks[index];
            return _buildActiveTaskItem(task);
          },
        );
      },
    );
  }

  // 构建已完成的任务列表
  Widget _buildCompletedTasksList() {
    // 日志输出已关闭
    // print('构建已完成任务列表组件');
    return StreamBuilder<List<UploadTask>>(
      key: _completedStreamKey,
      stream: ChunkUploadService.uploadTasksStream,
      initialData: ChunkUploadService.uploadTasks,
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text('正在加载...'),
              ],
            ),
          );
        }

        final tasks = List<UploadTask>.from(ChunkUploadService.uploadTasks);
        print('已完成任务列表 - 获取最新数据 - 总任务数: ${tasks.length}');

        final completedTasks =
            tasks.where((task) {
              final isCompleted =
                  task.status == UploadTaskStatus.completed ||
                  task.status == UploadTaskStatus.canceled;
              print(
                '【已完成】检查任务 ${task.fileName} - 状态: ${task.status}, 是否完成: $isCompleted',
              );
              return isCompleted;
            }).toList();

        // 按完成时间倒序排序
        completedTasks.sort(
          (a, b) => (b.completedAt ?? b.createdAt).compareTo(
            a.completedAt ?? a.createdAt,
          ),
        );

        print('已完成任务数: ${completedTasks.length}');

        if (completedTasks.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ShaderMask(
                  shaderCallback: (Rect bounds) {
                    return LinearGradient(
                      colors: [
                        Theme.of(context).colorScheme.primary,
                        Theme.of(context).colorScheme.secondary,
                      ],
                    ).createShader(bounds);
                  },
                  child: const Icon(Icons.task_alt, size: 64),
                ),
                const SizedBox(height: 16),
                Text(
                  '没有已完成的上传任务',
                  style: TextStyle(
                    fontSize: 16,
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          key: ValueKey(
            'completed_tasks_${DateTime.now().millisecondsSinceEpoch}',
          ),
          itemCount: completedTasks.length,
          padding: const EdgeInsets.all(16),
          itemBuilder: (context, index) {
            final task = completedTasks[index];
            return _buildCompletedTaskItem(task);
          },
        );
      },
    );
  }

  // 构建进行中任务的列表项
  Widget _buildActiveTaskItem(UploadTask task) {
    final theme = Theme.of(context);
    final bool isUploading = task.status == UploadTaskStatus.uploading;
    final bool isPaused = task.status == UploadTaskStatus.paused;
    final bool isFailed = task.status == UploadTaskStatus.failed;

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: theme.colorScheme.outlineVariant.withOpacity(0.5),
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  _getFileIcon(task.fileName),
                  color: theme.colorScheme.primary,
                  size: 24,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        task.fileName,
                        style: theme.textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.w500,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        task.formattedSize,
                        style: theme.textTheme.bodySmall?.copyWith(
                          color: theme.colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: LinearProgressIndicator(
                value: task.progress / 100,
                backgroundColor: theme.colorScheme.surfaceVariant,
                valueColor: AlwaysStoppedAnimation<Color>(
                  isFailed
                      ? theme.colorScheme.error
                      : isPaused
                      ? theme.colorScheme.tertiary
                      : theme.colorScheme.primary,
                ),
                minHeight: 8,
              ),
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _getStatusText(task.status),
                  style: theme.textTheme.bodyMedium?.copyWith(
                    color:
                        isFailed
                            ? theme.colorScheme.error
                            : theme.colorScheme.onSurfaceVariant,
                  ),
                ),
                Row(
                  children: [
                    if (isUploading)
                      IconButton(
                        icon: const Icon(Icons.pause),
                        onPressed:
                            () => ChunkUploadService.pauseUploadTask(task.id),
                        tooltip: '暂停',
                        color: theme.colorScheme.primary,
                      )
                    else if (isPaused || isFailed)
                      IconButton(
                        icon: const Icon(Icons.play_arrow),
                        onPressed:
                            () => ChunkUploadService.resumeUploadTask(task.id),
                        tooltip: '继续',
                        color: theme.colorScheme.primary,
                      ),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed:
                          () => ChunkUploadService.cancelUploadTask(task.id),
                      tooltip: '取消',
                      color: theme.colorScheme.error,
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建已完成任务的列表项
  Widget _buildCompletedTaskItem(UploadTask task) {
    final theme = Theme.of(context);
    final bool isCanceled = task.status == UploadTaskStatus.canceled;

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: theme.colorScheme.outlineVariant.withOpacity(0.5),
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Icon(
              _getFileIcon(task.fileName),
              color:
                  isCanceled
                      ? theme.colorScheme.error
                      : theme.colorScheme.primary,
              size: 24,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    task.fileName,
                    style: theme.textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.w500,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      Text(
                        task.formattedSize,
                        style: theme.textTheme.bodySmall?.copyWith(
                          color: theme.colorScheme.onSurfaceVariant,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Container(
                        width: 4,
                        height: 4,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: theme.colorScheme.onSurfaceVariant,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        _getStatusText(task.status),
                        style: theme.textTheme.bodySmall?.copyWith(
                          color:
                              isCanceled
                                  ? theme.colorScheme.error
                                  : theme.colorScheme.primary,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Container(
                        width: 4,
                        height: 4,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: theme.colorScheme.onSurfaceVariant,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        _formatDateTime(task.completedAt ?? task.createdAt),
                        style: theme.textTheme.bodySmall?.copyWith(
                          color: theme.colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            IconButton(
              icon: const Icon(Icons.delete_outline),
              onPressed: () => ChunkUploadService.removeUploadTask(task.id),
              tooltip: '删除',
              color: theme.colorScheme.error,
            ),
          ],
        ),
      ),
    );
  }

  // 获取文件图标
  IconData _getFileIcon(String fileName) {
    final extension = fileName.split('.').last.toLowerCase();
    switch (extension) {
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
      case 'webp':
        return Icons.image;
      case 'mp4':
      case 'avi':
      case 'mov':
      case 'wmv':
        return Icons.video_file;
      case 'mp3':
      case 'wav':
      case 'ogg':
      case 'flac':
        return Icons.audio_file;
      case 'pdf':
        return Icons.picture_as_pdf;
      case 'doc':
      case 'docx':
      case 'txt':
        return Icons.description;
      case 'xls':
      case 'xlsx':
        return Icons.table_chart;
      case 'zip':
      case 'rar':
      case '7z':
        return Icons.folder_zip;
      default:
        return Icons.insert_drive_file;
    }
  }

  // 获取状态文本
  String _getStatusText(UploadTaskStatus status) {
    switch (status) {
      case UploadTaskStatus.pending:
        return '等待上传';
      case UploadTaskStatus.uploading:
        return '正在上传';
      case UploadTaskStatus.paused:
        return '已暂停';
      case UploadTaskStatus.completed:
        return '已完成';
      case UploadTaskStatus.failed:
        return '上传失败';
      case UploadTaskStatus.canceled:
        return '已取消';
    }
  }

  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}
